package com.njitzx.service.impl;

import com.njitzx.constant.MenuConstant;
import com.njitzx.constant.UserConstant;
import com.njitzx.entity.po.Permission;
import com.njitzx.entity.po.Role;
import com.njitzx.entity.vo.MenuVO;
import com.njitzx.mapper.PermissionMapper;
import com.njitzx.mapper.RoleMapper;
import com.njitzx.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<MenuVO> getMenusByUserId(Integer userId) {
        //首先去缓存中寻找
        String redisKey = MenuConstant.MENU_PREFIX + userId;
        List<MenuVO> menuVOS = (List<MenuVO>) redisTemplate.opsForValue().get(redisKey);
        if (menuVOS != null) {
            return menuVOS;
        }
        //得到了用户的id
        Role role = roleMapper.selectRole(userId);
        String[] split = role.getPsIds().split(","); //拿到所有的权限id
        //根据spilt拿到一级的权限
        List<Permission> permissions = permissionMapper.getPermisson(split);

        menuVOS = permissions.stream().filter(item -> item.getPsPid() == 0).map( //找到一级id
                item -> {
                    MenuVO menuVO = changeMenuVO(item); //筛选过后的
                    //取二级菜单                   //找的子一级id 等于上一级id
                    List<MenuVO> collect = permissions.stream()
                            .filter(item2 -> item2.getPsPid().equals(item.getPsId())).
                             map(this::changeMenuVO)
                            .collect(Collectors.toList());
                    menuVO.setChildren(collect);
                    return menuVO;
                }
        ).collect(Collectors.toList());
        redisTemplate.opsForValue().set(MenuConstant.MENU_PREFIX + userId, menuVOS);
        return menuVOS;
    }

    private MenuVO changeMenuVO(Permission item) {
        MenuVO menuVO = new MenuVO();
        menuVO.setId(item.getPsId());
        menuVO.setIcon(item.getPsC());
        menuVO.setPath(item.getPsApiPath());
        menuVO.setAuthName(item.getPsName());
        menuVO.setOrder(item.getPsApiOrder());

        return menuVO;
    }
}
